﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;

namespace MS.InformationManagement.Controls
{
    [ToolboxData("<{0}:LibraryRedirector runat=server></{0}:LibraryRedirector>")]
    public class LibraryRedirector : WebControl
    {
        protected override void OnLoad(EventArgs e)
        {
            string userName = SPContext.Current.Web.CurrentUser.LoginName;
            string libraryName = userName.Substring(userName.LastIndexOf('\\') + 1);

            SPList targetLibrary = SPContext.Current.Web.Lists.TryGetList(libraryName);
            if (targetLibrary != null)
            {
                Page.Response.Redirect(targetLibrary.Views[0].ServerRelativeUrl + "?InitialTabId=MSIM&VisibilityContext=WSSTabPersistence");
            }
            else {
                StringBuilder javascript = new StringBuilder(@"<script type='text/javascript'>");
                javascript.Append("ExecuteOrDelayUntilScriptLoaded(function(){");
                javascript.Append("var statusID = '';");
                javascript.Append("statusID=SP.UI.Status.addStatus('', 'Su usuario no se encuentra configurado en la plataforma. Por favor contacte al administrador del sitio');");
                javascript.Append("SP.UI.Status.setStatusPriColor(statusID, 'red');");
                javascript.Append("var pos = $('#pageStatusBar').offset();");
                javascript.Append("$('#s4-workspace').animate({scrollTop: pos.top});");
                javascript.Append("setTimeout(function(){SP.UI.Status.removeStatus(statusID); statusID=null;}, 6000);}, 'sp.js');");
                javascript.Append("</script>");
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "errorscript", javascript.ToString());
            }

            base.OnLoad(e);
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            base.RenderContents(output);
        }
    }
}
